package com.tjbklx1.thread.chap01.practice06;

import java.util.Random;

public class EaterThread extends Thread {

	private String name;
	private final Tool lefthand;
	private final Tool righthand;

	public EaterThread(String name, Tool lefthand, Tool righthand) {
		this.name = name;
		this.lefthand = lefthand;
		this.righthand = righthand;
	}

	@Override
	public void run() {
		while (true) {
			eat();
		}
	}

	// 根据给定顺序获取资源
	private void eat() {
		synchronized (lefthand) {
			System.out.println(name + " takes up" + lefthand + " (left)");
			try {
				Thread.sleep(new Random().nextInt(1000));
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			synchronized (righthand) {
				System.out.println(name + " takes up" + righthand + " (right)");
				System.out.println(name + " eat ....");
				System.out
						.println(name + " puts down" + righthand + " (right)");
			}
			System.out.println(name + " puts down" + lefthand + " (left)");
		}

	}

}
